//
//  HomeHeadTableViewCell.swift
//  EasePods
//
//  Created by 易先生 on 2024/4/25.
//

import UIKit

class HomeHeadTableViewCell: TableViewCell {
    
    var useTimeClick: (() -> Void)?
    
    private var cellModel: HomeHeadCellModel?

    override func makeUI() {
        super.makeUI()
        
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(iconImageView)
        self.contentView.addSubview(deviceNameStackView)
        deviceNameStackView.addArrangedSubview(deviceNameLabel)
        deviceNameStackView.addArrangedSubview(stateLabel)
        self.contentView.addSubview(macAddressLabel)
        self.contentView.addSubview(iconImageView)
        self.contentView.addSubview(leftLineView)
        self.contentView.addSubview(rightEarConnectView)
        self.contentView.addSubview(rightLineView)
        self.contentView.addSubview(leftEarConnectView)
        self.contentView.addSubview(easeConnectView)
        self.contentView.addSubview(useTimeStackView)
        self.contentView.addSubview(sliderView)
        self.contentView.addSubview(minVolumeImageView)
        self.contentView.addSubview(maxVolumeImageView)

        iconImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(4)
            make.centerX.equalToSuperview()
        }
        
        deviceNameStackView.snp.makeConstraints { make in
            make.top.equalTo(iconImageView.snp.bottom)
            make.centerX.equalToSuperview()
//            make.width.equalTo(kScreenWidth - 40)
        }
        
        macAddressLabel.snp.makeConstraints { make in
            make.top.equalTo(deviceNameLabel.snp.bottom).offset(6)
            make.centerX.equalToSuperview()
            make.width.equalTo(kScreenWidth - 40)
        }
        
        rightEarConnectView.snp.makeConstraints { make in
            make.top.equalTo(macAddressLabel.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
        }
        
        leftLineView.snp.makeConstraints { make in
            make.top.bottom.equalTo(rightEarConnectView)
            make.trailing.equalTo(rightEarConnectView.snp.leading).offset(-16)
            make.width.equalTo(0.5)
        }
                
        leftEarConnectView.snp.makeConstraints { make in
            make.trailing.equalTo(leftLineView.snp.leading).offset(-16)
            make.centerY.equalTo(rightEarConnectView)
        }
        
        rightLineView.snp.makeConstraints { make in
            make.top.bottom.equalTo(rightEarConnectView)
            make.leading.equalTo(rightEarConnectView.snp.trailing).offset(16)
            make.width.equalTo(0.5)
        }
        
        easeConnectView.snp.makeConstraints { make in
            make.leading.equalTo(rightLineView.snp.leading).offset(16)
            make.centerY.equalTo(rightEarConnectView)
        }
        
        useTimeStackView.snp.makeConstraints { make in
            make.top.equalTo(rightEarConnectView.snp.bottom).offset(20)
            make.leading.greaterThanOrEqualToSuperview().offset(20)
            make.centerX.equalToSuperview()
        }
        
        sliderView.snp.makeConstraints { make in
            make.top.equalTo(useTimeStackView.snp.bottom).offset(29)
            make.leading.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(8)
        }
        
        minVolumeImageView.snp.makeConstraints { make in
            make.top.equalTo(sliderView.snp.bottom).offset(10)
            make.leading.equalToSuperview().offset(22)
            make.bottom.equalToSuperview().offset(-27)
        }
        
        maxVolumeImageView.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-22)
            make.centerY.equalTo(minVolumeImageView)
        }
        
        self.useTimeStackView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(useTime)))
        
    }
    
    @objc private func useTime() {
        self.useTimeClick?()
    }
    
    @objc private func sliderValueChanged(slider: UISlider) {
        let volumeValue = slider.value
        self.cellModel?.setVolumeValue.accept(volumeValue)
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    override func bind(viewModel: Any) {
        super.bind(viewModel: viewModel)
        guard let viewModel = viewModel as? HomeHeadCellModel else {
            return
        }
        cellModel = viewModel
        viewModel.sliderValue.bind(to: sliderView.rx.value).disposed(by: rx.disposeBag)
        
        viewModel.isConnected.subscribe(onNext: { [weak self] isConnected  in
            guard let self = self else { return }
            
            self.sliderView.minimumTrackTintColor = isConnected ? R.color.volume_2_progress() : R.color.volume_3_disconnected()
            self.sliderView.setThumbImage( isConnected ? R.image.ic_volume_dot() : R.image.ic_volume_dot_disconnect(), for: .normal)
            self.stateLabel.text = isConnected ? R.string.localizable.home_connected_text(): R.string.localizable.home_connecting_text()
            self.easeConnectView.connectImageView.isHidden = isConnected ? true : false
            self.iconImageView.alpha = isConnected ? 1 : 0.5
            viewModel.batteryInfo.subscribe(onNext: { [weak self] batteryInfoModel in
                guard let self = self else { return }
                guard let batteryModel = batteryInfoModel else { return }
                
                if batteryModel.boxBattery > MAXBattaryChargingNum {
                    self.easeConnectView.connectImageView.isHidden = false
                    self.easeConnectView.quantityLabel.isHidden = true
                    self.easeConnectView.connectImageView.image = R.image.ic_home_charging()
                    self.easeConnectView.quantityLabel.isHidden = true
                } else {
                    self.easeConnectView.connectImageView.isHidden = true
                    self.easeConnectView.connectImageView.image = R.image.ic_home_unconnected()
                    self.easeConnectView.quantityLabel.isHidden = false
                    self.easeConnectView.quantityLabel.text = batteryModel.boxBattery>0 ? "\(batteryModel.boxBattery)%" : "--%"
                }
                
                viewModel.receiveEarPhoneConnectionState.subscribe(onNext: { earPhoneConnectionState in
                    guard let connectionState = earPhoneConnectionState else {
                        return
                    }
                    self.leftEarConnectView.connectImageView.isHidden = false
                    self.rightEarConnectView.connectImageView.isHidden = false
                    self.leftEarConnectView.connectImageView.isHidden = connectionState.leftEarAndPhoneConnection ? true : false
                    self.rightEarConnectView.connectImageView.isHidden = connectionState.rightEarAndPhoneConnection ? true : false
                    
                    if batteryModel.leftEarBattery > MAXBattaryChargingNum {
                        self.leftEarConnectView.connectImageView.image = R.image.ic_home_charging()
                        self.leftEarConnectView.connectImageView.isHidden = false
                        self.leftEarConnectView.quantityLabel.isHidden = true
                        self.leftEarConnectView.connectImageView.image = R.image.ic_home_charging()
                    } else {
                        self.leftEarConnectView.quantityLabel.isHidden = false
                        self.leftEarConnectView.quantityLabel.text = batteryModel.leftEarBattery > 0 ? "\(batteryModel.leftEarBattery)%" : "--%"
                        self.leftEarConnectView.connectImageView.isHidden = true
                        self.leftEarConnectView.connectImageView.image = R.image.ic_home_unconnected()
                    }
                    
                    if batteryModel.rightEarBattery > MAXBattaryChargingNum {
                        self.rightEarConnectView.quantityLabel.isHidden = true
                        self.rightEarConnectView.connectImageView.isHidden = false
                        self.rightEarConnectView.connectImageView.image = R.image.ic_home_charging()
                        self.rightEarConnectView.connectImageView.image = R.image.ic_home_charging()
                    } else {
                        self.rightEarConnectView.quantityLabel.isHidden = false
                        self.rightEarConnectView.quantityLabel.text = batteryModel.rightEarBattery > 0 ? "\(batteryModel.rightEarBattery)%" : "--%"
                        self.rightEarConnectView.connectImageView.isHidden = true
                        self.rightEarConnectView.connectImageView.image = R.image.ic_home_unconnected()
                    }
                    
                }).disposed(by: rx.disposeBag)

            }).disposed(by: rx.disposeBag)
            
        }).disposed(by: rx.disposeBag)
        
        viewModel.sliderValue.subscribe { [weak self] volume in
            guard let self = self else { return }
            self.sliderView.value = volume
        }.disposed(by: rx.disposeBag)
        
        viewModel.useTime.map { value in
            if value == nil {
                return R.string.localizable.home_earbuds_not_use_content()
            } else {
                return R.string.localizable.home_earbuds_use_time_today_content(value.hourAndMinTimeFormat)
            }
        }.bind(to: self.useTimeLabel.rx.text).disposed(by: rx.disposeBag)
        
        self.deviceNameLabel.text = Device.current()?.localName
        self.macAddressLabel.text = Device.current()?.macAddress
    }
    
    private lazy var iconImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.img_common_earcase()
        imageView.alpha = 0.5
        return imageView
    }()
    
    lazy var deviceNameStackView: StackView = {
        let view = StackView()
        view.alignment = .center
        view.axis = .horizontal
        view.spacing = 6
        return view
    }()
    
    lazy var deviceNameLabel: UILabel = {
        let label = UILabel()
        label.textColor = R.color.common_3_text()
        label.font = Fonts.boldSystemFont(ofSize: 16)
        return label
    }()
    
    
    lazy var stateLabel: UILabel = {
        let label = UILabel()
        label.textColor = R.color.common_3_text()
        label.text = R.string.localizable.home_connecting_text()
        label.font = Fonts.systemFont(ofSize: 12)
        return label
    }()
    
    lazy var macAddressLabel: UILabel = {
        let label = UILabel()
        label.textColor = R.color.common_23_text_second()
        label.font = Fonts.systemFont(ofSize: 12)
        label.numberOfLines = 0
        label.textAlignment = .center
        return label
    }()
    
    private lazy var useTimeStackView: StackView = {
        let view = StackView(arrangedSubviews: [useTimeLabel,moreImageView, View()])
        view.alignment = .center
        view.axis = .horizontal
        return view
    }()
    
    private lazy var useTimeLabel: Label = {
        let label = Label()
        label.font = Fonts.systemFont(ofSize: 14)
        label.textColor = R.color.use_time_1_text()
        return label
    }()
    
    private lazy var moreImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.ic_common_more_medium()
        return imageView
    }()
    
    private lazy var leftEarConnectView: HomeHeadConnectView = {
        let view = HomeHeadConnectView()
        view.iconImageView.image = R.image.ic_home_earbuds_battery_left()
        view.connectImageView.image = R.image.ic_home_unconnected()
        return view
    }()
    
    private lazy var leftLineView: View = {
        let view = View()
        view.backgroundColor = R.color.home_5_line()
        return view
    }()
    
    private lazy var rightLineView: View = {
        let view = View()
        view.backgroundColor = R.color.home_5_line()
        return view
    }()
    
    private lazy var rightEarConnectView: HomeHeadConnectView = {
        let view = HomeHeadConnectView()
        view.iconImageView.image = R.image.ic_home_earbuds_battery_right()
        view.connectImageView.image = R.image.ic_home_unconnected()
        return view
    }()
    
    private lazy var easeConnectView: HomeHeadConnectView = {
        let view = HomeHeadConnectView()
        view.iconImageView.image = R.image.ic_home_earcase_battery()
        view.connectImageView.image = R.image.ic_home_unconnected()
        return view
    }()
    
    private lazy var sliderView: CustomSlider = {
        let sliderView = CustomSlider()
        sliderView.minimumTrackTintColor = R.color.volume_3_disconnected()
        sliderView.maximumTrackTintColor = R.color.volume_1_bg()
        sliderView.minimumValue = MinVolume
        sliderView.maximumValue = MaxVolume
        sliderView.addTarget(self, action: #selector(sliderValueChanged(slider:)), for: .touchUpInside)
        return sliderView
    }()
    
    private lazy var minVolumeImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.ic_volume_empty()
        return imageView
    }()
    
    private lazy var maxVolumeImageView: ImageView = {
        let imageView = ImageView()
        imageView.image = R.image.ic_volume_broad()
        return imageView
    }()
}

class CustomSlider: UISlider {
    override func trackRect(forBounds bounds: CGRect) -> CGRect {
        var newBounds = super.trackRect(forBounds: bounds)
        newBounds.size.height = 8 // 设置您想要的高度
        return newBounds
    }
}

class HomeHeadConnectView: View {
    
    override func makeUI() {
        super.makeUI()
        
        self.addSubview(mainStackView)
        mainStackView.snp.makeConstraints { make in
            make.leading.trailing.top.bottom.equalToSuperview()
        }
    }
    
    private lazy var mainStackView: StackView = {
        let view = StackView(arrangedSubviews: [iconImageView,quantityLabel,connectImageView])
        view.alignment = .center
        view.axis = .horizontal
        view.spacing = 4
        return view
    }()
    
    public lazy var iconImageView: ImageView = {
        let imageView = ImageView()
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    public lazy var quantityLabel: Label = {
        let label = Label()
        label.font = Fonts.systemFont(ofSize: 14)
        label.textColor = R.color.home_3_high_battery()
        label.text = "--%"
        return label
    }()
    
    public lazy var connectImageView: ImageView = {
        let imageView = ImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.isHidden = true
        return imageView
    }()
}
